/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.authorization.provider;


import com.luter.heimdall.core.authorization.provider.model.UserDO;
import com.luter.heimdall.core.exception.HeimdallException;
import com.luter.heimdall.core.utils.StrUtils;
import com.luter.heimdall.core.utils.crypto.Md5Util;

import java.util.List;

/**
 * 基于配置文件的权限管理控制
 *
 * @author luter
 */
public class DocumentUsersDataProvider {

    /**
     * Load user by user name user do.
     *
     * @param username the username
     * @return the user do
     */
    public static UserDO loadUserByUserName(String username) {
        if (StrUtils.isBlank(username)) {
            throw new HeimdallException("The Username must not be null");
        }
        List<UserDO> users = DocumentAuthorizationParser.parseUsers();
        if (null != users && !users.isEmpty()) {
            for (UserDO user : users) {
                if (username.equals(user.getUsername())) {
                    return user;
                }
            }
        }
        return null;
    }

    /**
     * Validate user user do.
     *
     * @param username the username
     * @param password the password
     * @return the user do
     */
    public static UserDO validateUser(String username, String password) {
        if (StrUtils.isBlank(username) || StrUtils.isBlank(password)) {
            throw new HeimdallException("username or password must not be null.");
        }
        List<UserDO> users = DocumentAuthorizationParser.parseUsers();
        if (null != users && !users.isEmpty()) {
            for (UserDO user : users) {
                if (username.equals(user.getUsername())) {
                    if (Md5Util.matches(password, user.getPassword())) {
                        return user;
                    }
                }
            }
        }
        throw new HeimdallException(" Your username or password was incorrect.");
    }

}
